package com.system.service.impl;

import com.sun.org.apache.regexp.internal.recompile;
import com.system.mapper.*;
import com.system.pojo.*;
import com.system.service.InvoiceService;
import com.system.service.LogisticsService;
import com.system.utils.UUIDUtil;
import com.system.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class InvoiceServiceImpl implements InvoiceService {

    @Autowired
    private InvoiceMapper invoiceMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private ContractGoodsMapper cgm;

    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Autowired
    private LogisticsMapper lm;



    @Override
    public boolean update(Integer uid, Integer invoiceId) {
//        ResultVo<Invoice> resultVo = new ResultVo<>();
        Invoice invoice = invoiceMapper.selectByPrimaryKey(invoiceId);
        invoice.setStoreAdminId(uid);
        invoice.setStatus(true);
        invoice.setSendTime(new Date());
        int i = invoiceMapper.updateByPrimaryKeySelective(invoice);
        //更新合同状态，履行中
        int i1 = contractMapper.updateStatusById(invoice.getContractId());
        if (i != 1 || i1 != 1){
            throw new RuntimeException();
        }
        //判断合同是否完成
        boolean finish = isContractFinish(invoice.getContractId());
        if (finish){
            contractMapper.updateFinishById(invoice.getContractId());
        }
        return true;
    }

    /**
     * 这方法有疑问，进货单确认之后才进货
     *
     * @param uid
     * @param invoiceId
     * @return
     */
    @Override
    public ResultVo<Invoice> deliver(Integer uid, Integer invoiceId) {
        ResultVo<Invoice> resultVo = new ResultVo<>();
        //判断商品数量与发货数量的关系
        //根据invoiceId获取发货单
        Invoice invoice = invoiceMapper.selectByPrimaryKey(invoiceId);
        int contractId = invoice.getContractId();
        int productId = invoice.getProductId();
        Product product = productMapper.selectByPrimaryKey(productId);
        int productRepertory = product.getRepertory();
        int sendCount = invoice.getSendCount();
        if (productRepertory < sendCount) {
            //产品数量小于发货数量
            //产品进货，生成进货单，如果产品正在进货，则不用生成进货单
            Purchase purchase = new Purchase();
            purchase.setProductId(productId);
            purchase.setCount(invoice.getSendCount());
            purchase.setInvoiceId(invoiceId);
            purchase.setPurchasePrice(product.getPrice());
            purchase.setPurchaseNum(UUIDUtil.uniqueString(20));
            int i = purchaseMapper.insertSelective(purchase);
			resultVo.setMessage("发货失败，商品库存不足，已通知进货");
			return resultVo;
        } else {
            product.setRepertory(productRepertory - sendCount);
        }
        //商品更新库存
        productMapper.updateByPrimaryKeySelective(product);
        //更新发货单
//        if (logisticsNumber == "0") {
//        	logisticsNumber = null;
//        }
        invoice.setStoreAdminId(uid);
        invoice.setStatus(true);
        invoice.setSendTime(new Date());
//        invoice.setLogisticsNumber(logisticsNumber);
        invoiceMapper.updateByPrimaryKeySelective(invoice);
//        Logistics logistics = new Logistics();
        
//        logistics.setLogisticsNumber(logisticsNumber);
//        logistics.setInvoiceId(invoiceId);
//        lm.insertSelective(logistics);
        //更新合同状态，履行中
        contractMapper.updateStatusById(contractId);
        //判断合同是否完成
        boolean finish = isContractFinish(invoice.getContractId());
        if (finish){
            contractMapper.updateFinishById(contractId);
        }
        resultVo.setUpdate(true);
        resultVo.setMessage("发货成功");
        return resultVo;
    }

    private boolean isContractFinish(Integer contractId) {
        List<ContractGoods> contractGoods = cgm.selectByContractId(contractId);
        boolean cf = true;
        for (ContractGoods contractGood : contractGoods) {
            if (contractGood.getStatus() == false){
                cf = false;
                break;
            }
        }
        if (cf == false){
            return false;
        }else{
            boolean inf = true;
            List<Invoice> invoices = invoiceMapper.selectByContractId(contractId);
            for (Invoice invoice : invoices) {
                if (invoice.getStatus() == false){
                    inf = false;
                    break;
                }
            }
            if (inf == false){
                return false;
            }
        }
        return true;
    }

    /**
     * 查询所有未发货的发货单
     *
     * @return
     */
    @Override
    public ResultVo<Invoice> selectAllUndone() {
        ResultVo<Invoice> resultVo = new ResultVo<>();
        List<Invoice> invoices = invoiceMapper.selectAllUndone();
        for (Invoice invoice : invoices) {
            Integer contractId = invoice.getContractId();
//            Integer storeAdminId = invoice.getStoreAdminId();
            Contract contract = contractMapper.selectWithClientAndSaler(contractId);
            invoice.setContract(contract);
        }
        resultVo.setTList(invoices);
        resultVo.setSelect(true);
        resultVo.setMessage("查询成功");
        return resultVo;
    }

    @Override
    public ResultVo<Invoice> selectAllDone() {
        ResultVo<Invoice> resultVo = new ResultVo<>();
        List<Invoice> invoices = invoiceMapper.selectAllDone();
        for (Invoice invoice : invoices) {
            Integer contractId = invoice.getContractId();
            Integer storeAdminId = invoice.getStoreAdminId();
            Contract contract = contractMapper.selectWithClientAndSaler(contractId);
            SysUser storeadmin = sysUserMapper.selectByPrimaryKey(storeAdminId);
            invoice.setContract(contract);
            invoice.setStoreadmin(storeadmin);
        }
        resultVo.setTList(invoices);
        resultVo.setSelect(true);
        resultVo.setMessage("查询成功");
        return resultVo;
    }

    @Override
    public ResultVo<Invoice> contractInvoices(Integer contractId) {
        return null;
    }

    @Override
    public ResultVo<Invoice> delete(Invoice invoice) {
    	ResultVo<Invoice> resultVo = new ResultVo<Invoice>();
//    	Integer contractId = invoice.getContractId();
    	Integer cgId = invoice.getCgId();
    	Integer sendCount = invoice.getSendCount();
    	ContractGoods cg = cgm.selectByPrimaryKey(cgId);
    	cg.addRest(sendCount);
    	cg.setStatus(false);
    	cgm.updateByPrimaryKeySelective(cg);
    	invoiceMapper.deleteByPrimaryKey(invoice.getId());
    	resultVo.setDelete(true);
    	resultVo.setMessage("删除成功");
    	return resultVo;
    }

    /*@Override
    public ResultVo<Invoice> contractInvoices(Integer contractId) {
        ResultVo<Invoice> resultVo = new ResultVo<>();
//        List<Invoice> invoices = invoiceMapper.invoicesByContractId(contractId);
//        resultVo.setTList(invoices);
        resultVo.setSelect(true);
        resultVo.setMessage("查询成功");
        return resultVo;
    }*/

    /*@Override
    public ResultVo<Invoice> deleteById(Integer invoiceId) {
        ResultVo<Invoice> resultVo = new ResultVo<>();
        Invoice invoice = invoiceMapper.selectByPrimaryKey(invoiceId);
        //删除这个发货单之后，还要更改合同信息，money
        Integer contractId = invoice.getContractId();
        Contract contract = contractMapper.selectByPrimaryKey(contractId);
        double sendMoney = invoice.getSendCount()*invoice.getSendPrice();
        contract.setMoney(contract.getMoney()-sendMoney);
        contractMapper.updateByPrimaryKeySelective(contract);
        invoiceMapper.deleteByPrimaryKey(invoiceId);
        resultVo.setDelete(true);
        resultVo.setMessage("删除成功");
        return resultVo;
    }*/

    @Override
    public ResultVo<Invoice> insert(ContractGoods cg) {
        ResultVo<Invoice> resultVo = new ResultVo<Invoice>();
        //添加发货单invoice
        Invoice invoice = new Invoice();
        invoice.setCgId(cg.getId());
        invoice.setContractId(cg.getContractId());
        invoice.setSendCount(cg.getInvoiceNum());
        invoice.setSendPrice(cg.getPurchasePrice());
        invoice.setSendNum(UUIDUtil.uniqueString(20));
        invoice.setProductName(cg.getProductName());//生成发货单时有发货单号
        invoice.setProductId(cg.getProductId());
        int i1 = invoiceMapper.insertSelective(invoice);
        
        //更改cg数据
        cg.sbuRest(cg.getInvoiceNum());
        int i = cgm.updateByPrimaryKeySelective(cg);
        
        //更改合同状态，正在履行
        int i2 = contractMapper.updateStatusById(cg.getContractId());
        if (i == 1 && i1 == 1 && i2 == 1){
            resultVo.setInsert(true);
            resultVo.setMessage("生成发货单成功");
        }else{
            throw new RuntimeException();
        }
        return resultVo;
    }

	@Override
	public ResultVo<Invoice> updateInvoice(Invoice invoice) {
		ResultVo<Invoice> resultVo = new ResultVo<Invoice>();
		//原数据库发货单信息
		Invoice invoice1 = invoiceMapper.selectByPrimaryKey(invoice.getId());
		//原数据库合同商品信息
		ContractGoods cg = cgm.selectByPrimaryKey(invoice1.getCgId());
		if (cg.getRest() == 0) {
			resultVo.setMessage("该购买的商品已全部生成");
		}
		Integer rest = cg.getRest();
		if (invoice1.getSendCount() + rest >= invoice.getNewSendCount()) {
			Integer addCount = invoice.getNewSendCount()-invoice1.getSendCount();
			cg.sbuRest(addCount);
			if(invoice1.getSendCount() + rest == invoice.getNewSendCount()) {
				cg.setStatus(true);
			}
			invoice1.setSendCount(invoice.getNewSendCount());
			invoice1.setSendNum(invoice.getSendNum());
			invoiceMapper.updateByPrimaryKeySelective(invoice1);
			cgm.updateByPrimaryKeySelective(cg);
			resultVo.setUpdate(true);
			resultVo.setMessage("修改发货单成功");
		}else {
			resultVo.setMessage("发货数量超过剩余未发货数量，修改失败");
		}
		return resultVo;
	}
}
